<?php
namespace app\login\controller;

use app\common\controller\Base;
use think\Request;
use think\Db;
use think\facade\Session;

/**
 * @title 登录（01-01）
 * @description 接口说明
 * @group 帐号中心（01）
 * @header name:model_id require:0 default:01 desc:秘钥(区别设置)
 * @groupremark 已使用错误码：1-01-01-0001 账号不存在或已禁用 1-01-01-0002 密码错误
 */
class Login extends Base
{
    /**
     *@title 登录
     *@description 接口说明
     *@author 开发者（陈庆锋）
     *@url /login/login/index
     *@method POST

     *@param name:username type:int require:1 default:1 other: desc:账号
     *@param name:password type:int require:1 default:1 other: desc:密码
     *@return data:帐号信息@!
     *@data token:token
     *
     */
    public function index()
    {
        //header('Access-Control-Allow-Origin:*');     //php允许跨域访问本接口.

        $data = input();

        //手机号填写规范
        $reg_phone = "/13[123569]{1}\d{8}|15[1235689]\d{8}|188\d{8}/";

        //邮箱填写规范
        $reg_email = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";

        $account = Db::name('account')
            ->whereOr('account',$data['username'])
            ->whereOr('phone',$data['username'])
            ->whereOr('email',$data['username'])
            ->find();


        //账号不存在
        if(!$account){
            $msg['error_id'] = '1-01-01-0001';
            $msg['msg'] = '账号不存在或已禁用';
            return $this->errorJson($msg);
        }

        //账号存在，验证密码
        if($account['password']==$data['password']){          //验证成功

            //随机生成20位字符串
            $token_str = substr(str_shuffle('abcedfghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'),0,20);

            //随机生成唯一id，7.1新特性，循环一亿次都没有重复
//            $token_str = session_create_id();

            //Session存储token,有效期60分钟,无前缀
            //Session::set('token',$token_str);

            //token表需要的字段
            $token['account_id'] = $account['id'];
            $token['token'] = $token_str;
            $token['expires_in'] = 3600;             //有效期60分钟
            $token['create_time'] = time();
            $token['end_time'] = $token['create_time'] + $token['expires_in'];

            //写入token表
            Db::name('token')->insert($token);

            if($account['type']===0){     //普通用户
                $msg['msg'] = '登录成功';
                $msg['data']['token'] = $token_str;
                return $this->successJson($msg);
            }else{                        //后台管理者
                $msg['token'] = $token_str;
                return $this->successJson($msg);
            }
        }else{           //密码错误
            $msg['error_id'] = '1-01-01-0002';
            $msg['msg'] = '密码错误';
            $msg['data'] = array();
            return $this->errorJson($msg);
        }
    }

   /*
    * 获取账号id
    */
    public function getAccountId($token){
        $msg['account_id'] = Db::name('token')->where('token',$token)->find()['account_id'];
        return $this->successJson($msg);
    }
}
